<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-group"></i> 前端用户管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-input v-model="search.authorNo" placeholder="作者号" class="handle-input mb10" clearable></el-input>
        <el-input v-model="search.loginName" placeholder="用户登录名" class="handle-input mb10" clearable></el-input>
        <el-input v-model="search.nickname" placeholder="用户昵称" class="handle-input" clearable></el-input>
        <el-input v-model="search.mobile" placeholder="手机号" class="handle-input" clearable></el-input>
        <el-date-picker v-model="search.createTimeRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" class="handle-input mr10" format="YYYY-MM-DD" clearable></el-date-picker>
        <!-- <el-select v-model="search.status" placeholder="用户状态" class="handle-input" clearable>
          <el-option label="未冻结" value="1"></el-option>
          <el-option label="冻结" value="0"></el-option>
        </el-select> -->
        <el-button type="primary" icon="el-icon-search" @click="getData()">搜索</el-button>
        <el-button type="primary" icon="el-icon-lx-friendadd" @click="showAddUser = true">添加用户 </el-button>

        <!-- <el-button type="primary" @click="freeze()"
          :disabled="!freezeList || freezeList.length === 0">批量冻结/解冻</el-button> -->
        <!-- <el-button type="primary" @click="exportMember()">导出用户数据</el-button> -->
        <!-- <el-button type="primary" @click="allBanSpeak()">全员禁言</el-button>
        <el-button type="primary" @click="allNoBanSpeak()">解除全员禁言</el-button> -->

      </div>
      <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header" @selection-change="handleSelectionChange" @select-all="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="userId" label="用户ID"></el-table-column>
        <el-table-column prop="loginName" label="用户名"></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column prop="nickname" label="用户昵称"></el-table-column>
        <el-table-column prop="wxOpenId" label="微信openID">
          <template #default="scope">
            <span>{{ scope.row.wxOpenId || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="qqOpenId" label="qqOpenId">
          <template #default="scope">
            <span>{{ scope.row.qqOpenId || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="userPic" label="用户头像">
          <template #default="scope">
            <img v-if="scope.row.userPic" :src="scope.row.userPic" style="width: 40px; height: 40px; border-radius: 50%;" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" :formatter="dateFormat"></el-table-column>
        <el-table-column prop="shareFer" label="推荐人">
          <template #default="scope">
            <span>{{ scope.row.shareFer || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="inviteCode" label="邀请码" align="center"></el-table-column>
        <el-table-column label="用户状态">
          <template #default="scope">
            <el-tag>{{ scope.row.status == '0' ? '冻结' : '未冻结' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="text" @click="edit_node(scope.row)">资金充值</el-button>
            <!-- <el-button type="text" @click="cheak_balance(scope.row)">查看余额</el-button> -->
            <!-- <el-button type="text" @click="cheak_achievement(scope.row)">查看团队数据</el-button> -->
            <!-- <el-button type="text" @click="cheakLowerLevel(scope.row)">查看下级</el-button> -->
            <!-- <el-button type="text" @click="LevelEdit(scope.row)">修改等级</el-button> -->
            <el-button type="text" @click="updateUser(scope.row)">修改用户信息</el-button>
            <el-button type="text" @click="editPassword(scope.row)">修改登录密码</el-button>
            <!-- <el-button type="text" @click="editSecondaryPassword(scope.row)">修改二级密码</el-button> -->
            <el-button type="text" @click="viewPets(scope.row)">查看宠物</el-button>
            <el-button type="text" @click="viewMoments(scope.row)">查看动态</el-button>
            <el-button type="text" @click="viewCommunity(scope.row)">查看动态社区</el-button>
            <el-button type="text" @click="viewRewards(scope.row)">查看打赏记录</el-button>
            <el-button type="text" @click="viewActivities(scope.row)">查看活动记录</el-button>
            <el-button type="text" @click="freezeOne(scope.row)">{{ scope.row.status == '0' ? '解冻' : '冻结' }}</el-button>
            <!-- <el-button type="text" @click="banSpeak(scope.row)">{{ scope.row.isProhibitSpeak == '0' ? '禁言' : '解除禁言'
            }}</el-button> -->
            <!-- <el-button type="text" @click="cheak_password(scope.$index, scope.row)">查看密码</el-button> -->
            <!-- <el-button type="text" @click="deleteUser(scope.row)">删除用户</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex" :page-size="query.pageSize" :total="query.pageTotal" @current-change="handlePageChange"></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="创建用户" v-model="showAddUser" width="30%">
      <el-form ref="form" :model="userlist" label-width="70px">
        <el-form-item label="手机号"> <el-input v-model="userlist.mobile"></el-input> </el-form-item>
        <el-form-item label="用户名称"> <el-input v-model="userlist.nickname"></el-input> </el-form-item>
        <el-form-item label="邀请码"> <el-input v-model="userlist.inviteCode"></el-input> </el-form-item>
        <!-- <el-form-item label="接点人手机号"> <el-input v-model="userlist.contactMobile"></el-input> </el-form-item> -->
        <el-form-item label="密码"> <el-input type="password" v-model="userlist.mm"></el-input> </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddUser = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="修改用户等级" v-model="showLevelEdit" width="30%">
      <el-form ref="form" label-width="70px">
        <el-form-item label="用户等级">
          <el-select v-model="levelFrom.superMember"> <el-option v-for="item in superMemberList" :key="item.id" :label="item.memberName" :value="item.id" /> </el-select>
        </el-form-item>
        <!-- <el-form-item label="团队等级">
          <el-select  v-model="levelFrom.member">
            <el-option v-for="item in memberList" :key="item.id" :label="item.teamName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showLevelEdit = false">取 消</el-button>
          <el-button type="primary" @click="LevelEditConfirm()">确 定</el-button>
        </span>
      </template>
    </el-dialog>



    <el-dialog title="用户下级" v-model="showLowerLevel" width="80%">
      <el-table :data="LowerLevelList" border class="table" ref="multipleTable" header-cell-class-name="table-header" @selection-change="handleSelectionChange" row-key="id" lazy :load="load" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="mobile" label="登录名"></el-table-column>
        <!-- <el-table-column prop="realName" label="真实姓名"></el-table-column> -->
        <!-- <el-table-column prop="member" label="用户等级"> <template #default="scope"> <el-tag>{{ scope.row.memberName }}</el-tag>  </template>  </el-table-column> -->
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showLowerLevel = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="修改用户信息" v-model="showupdateUser" width="40%">
      <el-form ref="form" label-width="160px">
        <el-form-item label="用户头像">
          <el-upload class="avatar-uploader" :action="uploadAction" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :http-request="customUpload">
            <div v-if="updateUserFrom.fileUrl" class="avatar-container">
              <img :src="updateUserFrom.fileUrl" class="avatar">
              <div class="avatar-overlay">
                <i class="el-icon-delete avatar-delete-icon" @click.stop="deleteAvatar"></i>
              </div>
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div style="margin-top: 10px; color: #999; font-size: 12px;">
            支持 JPG、PNG 格式，文件大小不超过 2MB
          </div>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="updateUserFrom.nickname" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="简介">
          <el-input type="textarea" v-model="updateUserFrom.description" placeholder="请输入用户简介" :rows="3" />
        </el-form-item>
        <el-form-item label="核销人员">
          <el-radio-group v-model="updateUserFrom.isWriteOffPersonnel">
            <el-radio :label="0">非核销人员</el-radio>
            <el-radio :label="1">核销人员</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showupdateUser = false">取 消</el-button>
          <el-button type="primary" @click="editUpdateUser" :loading="updateLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑弹出框 -->
    <el-dialog title="资金充值" v-model="show_node" width="65%">
      <el-form ref="form" :model="form_node" label-width="100px">
        <el-form-item label="用户信息">
          <div>{{ form_node.nickname || form_node.loginName || '未知用户' }}({{ form_node.userId }})</div>
        </el-form-item>
        <el-form-item label="资金类型">
          <el-select v-model="form_node.kindId" placeholder="选择资金类型">
            <el-option v-for="item in kindList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易金额">
          <el-input v-model="form_node.money" type="number" placeholder="请输入交易金额" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="form_node.type" placeholder="请选择类型" class="handle-input">
            <el-option label="手动操作" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form_node.status">
            <el-radio :label="0">减</el-radio>
            <el-radio :label="1">加</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="show_node = false">取 消</el-button>
          <el-button type="primary" @click="confirm_node">确 定</el-button>
        </span>
      </template>
    </el-dialog>



    <!-- 打赏记录弹窗 -->
    <el-dialog title="打赏记录" v-model="showRewardDialog" width="90%">
      <div v-if="currentUser.userId" style="margin-bottom: 15px;">
        <strong>用户信息：</strong>{{ currentUser.nickname || currentUser.loginName || '未知用户' }}({{ currentUser.userId }})
      </div>
      <el-table :data="rewardList" border class="table" header-cell-class-name="table-header">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="tradeUser" label="用户ID"></el-table-column>
        <el-table-column prop="orderTradeId" label="订单号"></el-table-column>
        <el-table-column prop="tradeGoodsName" label="礼物名称"></el-table-column>
        <el-table-column prop="tradeImgUrl" label="礼物图片" width="80">
          <template #default="scope">
            <el-image v-if="scope.row.tradeImgUrl" :src="scope.row.tradeImgUrl" :preview-src-list="[scope.row.tradeImgUrl]" style="width: 50px; height: 50px; border-radius: 6px;" fit="cover" :lazy="true" :hide-on-click-modal="true" :preview-teleported="true">
              <template #error>
                <div class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </template>
              <template #placeholder>
                <div class="image-slot">
                  <i class="el-icon-loading"></i>
                </div>
              </template>
            </el-image>
            <span v-else style="color: #999;">-</span>
          </template>
        </el-table-column>
        <el-table-column label="价格">
          <template #default="scope">
            <div style="line-height: 1.4;">
              <div>单价：{{ scope.row.tradePrice || '-' }}</div>
              <div>数量：{{ scope.row.tradeNumber || '-' }}</div>
              <div>总价：{{ scope.row.tradeMoney || '-' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="payWay" label="支付方式">
          <template #default="scope">
            <span v-if="scope.row.payWay === 1">支付宝</span>
            <span v-else-if="scope.row.payWay === 2">微信</span>
            <span v-else-if="scope.row.payWay === 3">衫德</span>
            <span v-else-if="scope.row.payWay === 4">余额</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="tradeStatus" label="支付状态">
          <template #default="scope">
            <el-tag v-if="scope.row.tradeStatus === 0" type="info">待支付</el-tag>
            <el-tag v-else-if="scope.row.tradeStatus === 1" type="success">已支付</el-tag>
            <el-tag v-else-if="scope.row.tradeStatus === 2" type="warning">已取消</el-tag>
            <el-tag v-else-if="scope.row.tradeStatus === 3" type="danger">已退款</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="refundStatus" label="退款状态">
          <template #default="scope">
            <el-tag v-if="scope.row.refundStatus === 0" type="info">未退款</el-tag>
            <el-tag v-else-if="scope.row.refundStatus === 1" type="warning">已申请</el-tag>
            <el-tag v-else-if="scope.row.refundStatus === 2" type="success">已同意</el-tag>
            <el-tag v-else-if="scope.row.refundStatus === 3" type="danger">拒绝</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="tradeTime" label="订单创建时间" :formatter="dateFormat"></el-table-column>
        <el-table-column prop="payTime" label="支付时间">
          <template #default="scope">
            <span>{{ scope.row.payTime ? dateFormat(scope.row, { property: 'payTime' }) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="refundTime" label="退款时间">
          <template #default="scope">
            <span>{{ scope.row.refundTime ? dateFormat(scope.row, { property: 'refundTime' }) : '-' }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="rewardList.length === 0" style="text-align: center; padding: 40px; color: #999;">
        暂无打赏记录
      </div>
      <div class="pagination" v-if="rewardQuery.pageTotal > 0">
        <el-pagination background layout="total, prev, pager, next" :current-page="rewardQuery.pageNo" :page-size="rewardQuery.pageSize" :total="rewardQuery.pageTotal" @current-change="handleRewardPageChange">
        </el-pagination>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRewardDialog = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { deleteSub, subN, api, apiEx, updateSub, aliImageUpload } from "@/api/index";
import { getRewardOrders } from "@/api/content";
import { formatDate } from "@/common/data";
import moment from "moment";
export default {
  inject: ["reload"],
  filters: {
    formatDate(time) {
      time = time * 1000;
      let date = new Date(time);
      console.log(new Date(time));
      return formatDate(date, "yyyy-MM-dd hh:mm");
    },
  },
  name: "basetable",
  data() {
    return {
      query: { pageNo: 1, pageTotal: 0, },
      tableData: [],
      search: {
        authorNo: '',
        loginName: '',
        nickname: '',
        mobile: '',
        createTimeRange: [],
        status: ''
      },
      freezeList: [],
      LowerLevelList: [],
      treeList: [],
      showAddUser: false,
      showupdateUser: false,
      showLowerLevel: false,
      showLevelEdit: false,
      password: "",
      form: {},
      updateUserFrom: {},
      levelFrom: {},
      userlist: {},
      superMemberList: [],
      memberList: [],
      show_node: false,
      kindList: [],
      form_node: { kindId: '1', type: 0 },
      showRewardDialog: false,
      rewardList: [],
      currentUser: {},
      rewardQuery: { pageNo: 1, pageTotal: 0, pageSize: 10 },

      // 上传相关
      uploadAction: '',
      updateLoading: false
    };
  },
  created() {
    this.getData();
    this.getLevel()
    this.getKindList()
  },
  methods: {
    // 格式化日期为 YYYY-MM-DD 格式
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 时间过滤器
    dateFormat: function (row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    handleSelectionChange(selection) {
      let list = []
      for (let i = 0; i < selection.length; i++) { list.push(selection[i].id); }
      this.freezeList = list
    },
    // 获取列表数据
    getData() {
      // 处理日期区间
      let startTime = '';
      let endTime = '';
      if (this.search.createTimeRange && this.search.createTimeRange.length === 2) {
        // 格式化日期为 YYYY-MM-DD 格式
        startTime = this.formatDate(this.search.createTimeRange[0]);
        endTime = this.formatDate(this.search.createTimeRange[1]);
      }

      api('/admin/subscribers/subList', {
        limit: 10,
        offset: this.query.pageNo,
        pid: this.$store.state.adminMsg.parentId,
        authorNo: this.search.authorNo,
        loginName: this.search.loginName,
        nickname: this.search.nickname,
        mobile: this.search.mobile,
        startTime: startTime,
        endTime: endTime,
        status: this.search.status,
      }).then((res) => {
        this.tableData = res.data.rows;
        this.query.pageTotal = res.data.total;
      });
    },
    getKindList() {
      api('/web/daKind/s').then((res) => { this.kindList = res.data });
    },
    getLevel() {
      api('/admin/usersMemberConfig/select', { parentId: this.$store.state.adminMsg.parentId, }).then((res) => { this.superMemberList = res.data });
    },

    freeze() {
      if (!this.freezeList || this.freezeList.length === 0) {
        this.$message.warning("请先选择要操作的用户");
        return;
      }
      this.$confirm(`确定要批量冻结/解冻选中的 ${this.freezeList.length} 个用户吗？`, "提示", { type: "warning", }).then(() => {
        api('/admin/subscribers/subDJ', { id: this.freezeList, }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message);
            this.$refs.multipleTable.clearSelection();
            this.reload()
          } else {
            this.$message.error(res.message);
          }
        });
      }).catch(() => { });
    },
    freezeOne(row) {
      this.$confirm("确定要冻结/解冻用户吗？", "提示", { type: "warning", }).then(() => {
        api('/admin/subscribers/subDJ', { id: row.id, }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message);
            this.reload()
          } else {
            this.$message.error(res.message);
          }
        });
      }).catch(() => { });
    },
    // 单个成员禁言
    banSpeak(row) {
      this.$confirm(row.isProhibitSpeak == 1 ? '解除该用户禁言' : '将该用户禁言', "提示", { type: "warning", }).then(() => {
        api('/web/prohibitSpeak/sps', { isProhibitSpeak: row.isProhibitSpeak == 1 ? 0 : 1, userId: row.userId }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message);
            this.reload()
          } else {
            this.$message.error(res.message);
          }
        });
      });
    },
    deleteUser(row) {
      this.$confirm("该操作用户将不可找回", "确定删除该用户！", { type: "warning", }).then(() => {
        api('/web/capital/de', { userId: row.userId, }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message);
            this.reload()
          } else {
            this.$message.error(res.message);
          }
        });
      }).catch(() => { });
    },
    setSalesman(row) {
      this.$confirm("注意", "将该用户设置成为中介", { type: "warning", }).then(() => {
        api('/admin/subscribers/updateLevel', { id: row.id, isSalesman: 1 }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message);
            this.reload()
          } else {
            this.$message.error(res.message);
          }
        });
      }).catch(() => { });
    },

    // 分页导航
    handlePageChange(val) {
      this.query.pageNo = val;
      this.getData();
    },
    // 下拉搜索框
    changeType() {
      this.query.pageNo = 1
      this.getData();
    },

    //创建用户
    addUser() {
      api('/admin/subscribers/subC', {
        mm: this.userlist.mm,
        mobile: this.userlist.mobile,
        nickname: this.userlist.nickname,
        contactMobile: this.userlist.contactMobile,
        inviteCode: this.userlist.inviteCode,
        parentId: this.$store.state.adminMsg.parentId,
      }).then((res) => {
        if (res.code === 2000) {
          this.$message.success("新增用户成功");
          this.userlist = {};
          this.showAddUser = false;
          this.reload();
        } else {
          this.$message.error(res.message);
        }
      });
    },

    // 查看下级
    cheakLowerLevel(v) {
      this.showLowerLevel = true;
      api('/admin/subscribers/subN', {
        userId: v.userId,
      }).then((res) => {
        this.LowerLevelList = res.data;
      });
    },
    /* 查看下级 -> 树形表格懒加载 */
    load(tree, treeNode, resolve) {
      api('/admin/subscribers/subN', {
        userId: tree.id,
      }).then((res) => {
        this.treeList = res.data;
      });
      setTimeout(() => {
        resolve(this.treeList);
      }, 1000);
    },

    // 查看余额
    cheak_balance(row) {
      api('/web/capital/m', {
        userId: row.userId,
      }).then((res) => {
        this.$alert(
          `<div>兑换券：${res.data.a} </div>  <div>消费券：${res.data.c} </div>`,
          "查看用户余额", { dangerouslyUseHTMLString: true }
        );
      });
    },


    // 查看密码
    cheak_password(v) {
      console.log(v);
      this.$alert(
        `<div>用户密码：${v.password} </div>`,
        "查看用户密码", { dangerouslyUseHTMLString: true }
      );
    },
    //  查看业绩
    cheak_achievement(row) {
      console.log(row);
      api('/web/capital/a', { userId: row.userId, }).then((res) => {
        this.$alert(
          ` <div>等级：${res.data.a}</div>
        <div>引流人数：${res.data.b} </div>
        <div>引流成交量：${res.data.c} </div>
        <div>团队业绩：${res.data.d} </div> `,
          "查看团队数据", { dangerouslyUseHTMLString: true });
      });
    },

    // 显示修改等级模块
    LevelEdit(v) {
      this.showLevelEdit = true;
      this.levelFrom = v;
    },
    // 修改用于等级
    LevelEditConfirm() {
      api('/admin/subscribers/updateLevel', this.levelFrom).then((res) => {
        if (res.code === 2000) {
          this.$message.success(res.message);
          this.showLevelEdit = false;
          this.getData()
        } else {
          this.$message.error(res.message);
        }
      });
      // api('/admin/subscribers/updateTeamLevel', this.levelFrom).then((res) => {
      //   if (res.code === 2000) {
      //     this.$message.success(res.message);
      //   } else {
      //     this.$message.error(res.message);
      //   }
      // });
      setTimeout(() => {
      }, 1000)
    },
    // 显示修改用户信息
    updateUser(v) {
      this.showupdateUser = true;
      // 深拷贝用户数据，避免直接修改原数据
      this.updateUserFrom = {
        ...v,
        fileUrl: v.userPic || '', // 使用现有头像
        fileThumbnailsUrl: v.userPic || '', // 缩略图默认使用相同地址
        description: v.description || '',
        isWriteOffPersonnel: v.isWriteOffPersonnel || 0
      };
    },
    // 修改用户信息
    editUpdateUser() {
      this.updateLoading = true;

      // 构建更新数据，根据图片中的字段结构
      const updateData = {
        id: this.updateUserFrom.id,
        userId: this.updateUserFrom.userId,
        nickname: this.updateUserFrom.nickname,
        description: this.updateUserFrom.description,
        fileUrl: this.updateUserFrom.fileUrl, // 头像地址
        fileThumbnailsUrl: this.updateUserFrom.fileThumbnailsUrl, // 头像缩略图地址
        isWriteOffPersonnel: this.updateUserFrom.isWriteOffPersonnel,
      };

      updateSub(updateData).then((res) => {
        this.updateLoading = false;
        if (res.code === 2000) {
          this.$message.success("修改成功");
          this.showupdateUser = false;
          this.getData();
        } else {
          this.$message.error(res.message || "修改失败");
        }
      }).catch((error) => {
        this.updateLoading = false;
        this.$message.error("修改失败");
        console.error('更新用户信息失败:', error);
      });
    },

    // 修改用户密码
    editPassword(v) {
      this.$prompt('请输入新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        api('/admin/subscribers/updatePassword', {
          userId: v.userId,
          password: this.getPass(value),
          parentId: this.$store.state.adminMsg.parentId,
        }).then((res) => {
          if (res.code == 2000) {
            this.$message.success(res.message);
          } else {
            this.$message.error(res.message);
          }
        });
      })
    },
    // 修改用户密码
    editSecondaryPassword(v) {
      this.$prompt('请输入新二级密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        api('/admin/subscribers/updateSecondaryPassword', {
          userId: v.userId,
          secondaryPassword: this.getPass(value),
          parentId: this.$store.state.adminMsg.parentId,
        }).then((res) => {
          if (res.code == 2000) {
            this.$message.success(res.message);
          } else {
            this.$message.error(res.message);
          }
        });
      })
    },

    exportar(v) {
      this.$confirm('接点伞下业绩导出', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        apiEx('/web/so/sae', {
          userId: v.userId
        }).then((res) => {
          const blob = new Blob([res]); // 创建blob对象
          const fileName = "接点伞下业绩.xlsx";
          const elink = document.createElement("a"); // 创建的标签
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = URL.createObjectURL(blob); // 创建url
          document.body.appendChild(elink); // 把 创建的标签追加到body里
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink); // 移除标签
          this.$message({
            message: "导出成功！！！",
            type: "success",
          });
          this.$refs.multipleTable.clearSelection();
        });
      })
    },

    // 全局禁言
    allBanSpeak() {
      this.$confirm("注意", "该操作将全体成员禁言！！！", { type: "warning", }).then(() => {
        api('/web/prohibitSpeak/ops', { isProhibitSpeak: 1 }).then((res) => { this.$message.success(res.message); });
      })
    },
    // 全局解除禁言
    allNoBanSpeak() {
      this.$confirm("注意", "该操作将接触全体成员禁言！！！", { type: "warning", }).then(() => {
        api('/web/prohibitSpeak/ops', { isProhibitSpeak: 0 }).then((res) => { this.$message.success(res.message); });
      })
    },

    exportMember() {
      apiEx('/web/capital/se', { exportType: 1, userId: 1 }).then((res) => {
        const blob = new Blob([res]); // 创建blob对象
        const fileName = "用户数据.xlsx";
        const elink = document.createElement("a"); // 创建的标签
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob); // 创建url
        document.body.appendChild(elink); // 把 创建的标签追加到body里
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 移除标签
        this.$message({
          message: "导出成功！！！",
          type: "success",
        });
        this.$refs.multipleTable.clearSelection();
      });
    },
    edit_node(v) {
      this.show_node = true;
      this.form_node = {
        ...v,
        kindId: 1, // 默认选择第一个资金类型
        type: 0, // 默认手动操作
        money: '',
        status: 1 // 默认加
      };
      console.log(this.form_node);
    },
    confirm_node() {
      if (!this.form_node.money) {
        this.$message.error('请输入交易金额');
        return;
      }
      if (this.form_node.type === undefined || this.form_node.type === null) {
        this.$message.error('请选择类型');
        return;
      }

      api('/web/cyBer/add', {
        kindId: this.form_node.kindId,
        money: this.form_node.money,
        status: this.form_node.status,
        type: this.form_node.type,
        userId: this.form_node.userId,
        loginName: this.form_node.mobile
      }).then((res) => {
        if (res.code === 2000) {
          this.$message.success(res.message);
          this.form_node = {};
          this.show_node = false;
          this.getData(); // 刷新列表数据
        } else {
          this.$message.error(res.message);
          this.form_node = {};
        }
      });
    },


    getPass(item) {
      //将password转化为Base64格式
      const Base64 = require("js-base64").Base64;
      const exStr = Base64.encode(item);
      let jse = new this.$jsEncrypt();
      // 加入rsa public key
      jse.setPublicKey(
        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChEuUwaHR5OsJ8EM3/8UwJCngMGwufVnAerVGMz6CLg7q9NDn9dUnr83suKZcCHKUpIvzBqJ05vy3zrYGuS1D4cCCIZiZEzN9I1AfllD1fKmcnz1tL56NWZ4HMfhjesAkjxa69Xmh6qYbIFanqHFkqNje+gZ5hDA8Om1/diT/NzwIDAQAB"
      );
      return jse.encrypt(exStr);
    },

    // 查看宠物
    viewPets(row) {
      this.$router.push({
        path: '/petManagement',
        query: { userId: row.userId }
      });
    },

    // 查看动态 - 跳转到动态管理页面
    viewMoments(row) {
      this.$router.push({
        path: '/momentsManagement',
        query: { userId: row.userId }
      });
    },

    // 查看动态社区
    viewCommunity(row) {
      this.$router.push({
        path: '/postManagement',
        query: { userId: row.userId }
      });
    },

    // 查看打赏记录
    viewRewards(row) {
      this.currentUser = row;
      this.showRewardDialog = true;
      this.rewardQuery.pageNo = 1; // 重置分页
      this.getRewardList();
    },

    // 获取打赏记录列表
    getRewardList() {
      getRewardOrders({
        userId: this.currentUser.userId,
        limit: this.rewardQuery.pageSize,
        offset: this.rewardQuery.pageNo
      }).then((res) => {
        this.rewardList = res.data.rows || [];
        this.rewardQuery.pageTotal = res.data.total || 0;
      }).catch(() => {
        this.rewardList = [];
        this.rewardQuery.pageTotal = 0;
      });
    },

    // 打赏记录分页切换
    handleRewardPageChange(val) {
      this.rewardQuery.pageNo = val;
      this.getRewardList();
    },

    // 查看活动记录
    viewActivities(row) {
      this.$router.push({
        path: '/activityOrder',
        query: { userId: row.userId }
      });
    },


    // 自定义上传方法
    customUpload(options) {
      const formData = new FormData();
      formData.append('file', options.file);

      aliImageUpload(formData).then((res) => {
        if (res.code === 2000 && res.data) {
          // 根据接口返回的数据结构设置图片地址
          this.updateUserFrom.fileUrl = res.data.imageUrl || "";
          this.updateUserFrom.fileThumbnailsUrl = res.data.thumbnailsUrl || "";

          this.$message.success('头像上传成功');
          options.onSuccess(res);
        } else {
          this.$message.error(res.message || '上传失败');
          options.onError(new Error(res.message || '上传失败'));
        }
      }).catch((error) => {
        console.error('上传失败:', error);
        this.$message.error('上传失败');
        options.onError(error);
      });
    },

    // 上传成功回调
    handleAvatarSuccess(res, file) {
      // 这个方法在customUpload中已经处理了，这里可以为空或添加额外逻辑
    },

    // 上传前验证
    beforeAvatarUpload(file) {
      const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGOrPNG) {
        this.$message.error('头像图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('头像图片大小不能超过 2MB!');
      }
      return isJPGOrPNG && isLt2M;
    },

    // 删除头像
    deleteAvatar() {
      this.updateUserFrom.fileUrl = '';
      this.updateUserFrom.fileThumbnailsUrl = '';
      this.$message.success('头像已删除');
    }

  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 250px;
  display: inline-block;
  margin-right: 10px;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

.mb10 {
  margin-bottom: 10px;
}

::v-deep .el-date-editor {
  margin-right: 10px;
  width: 350px;
}

::v-deep .el-date-editor.el-range-editor {
  width: 350px;
}

/* 头像上传样式 */
.avatar-uploader ::v-deep .el-upload {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.avatar-uploader ::v-deep .el-upload:hover {
  border-color: #409EFF;
  background-color: #f0f9ff;
}

.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  display: block;
}

.avatar-container {
  position: relative;
  width: 120px;
  height: 120px;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
  border-radius: 8px;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-delete-icon {
  position: absolute;
  top: 5px;
  right: 5px;
  font-size: 18px;
  color: #fff;
  background-color: rgba(255, 0, 0, 0.8);
  border-radius: 50%;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.avatar-delete-icon:hover {
  background-color: rgba(255, 0, 0, 1);
  transform: scale(1.1);
}
</style>
